package org.test4j.mock.startup;

import java.io.File;
import java.util.regex.Pattern;

/**
 * java-agent使用提示
 *
 * @author wudarui
 */
public class JavaAgentHits {

    private static final Pattern JAR_REGEX = Pattern.compile(".*fluent-mock[-._\\d]*(-SNAPSHOT)?.jar");
    private static final String Dep_Jar_Path = "fluent-mock.jar";

    private static String hits = null;

    private JavaAgentHits() {
    }

    /**
     * 返回 -javaagent:.../fluent-mock.xxx.jar 提示
     *
     * @return
     */
    public static String message() {
        if (hits != null) {
            return hits;
        }
        String jarPath = getJarPath();
        StringBuffer buff = new StringBuffer();
        buff.append("If fluent mock isn't initialized. Please check that your JVM is started with command option:")
            .append("\n\n==IDE JVM=====================")
            .append("\n\t-javaagent:" + jarPath)
            .append("\n\n==Maven maven-surefire-plugin=")
            .append("\n\t<configuration>")
            .append("\n\t\t<argLine>@{argLine} -javaagent:${settings.localRepository}/org/test4j/fluent-mock/${version}/fluent-mock-${version}.jar</argLine>")
            .append("\n\t</configuration>")
            .append("\n\n==gradle dependencies=========")
            .append("\n\tdependencies {")
            .append("\n\t\ttest {")
            .append("\n\t\t\tjvmArgs \"-javaagent:${classpath.find { it.name.contains(\"fluent-mock\") }.absolutePath}\"")
            .append("\n\t\t\tuseJUnitPlatform()")
            .append("\n\t\t}")
            .append("\n\t}")
            .append("\n================================");

        hits = buff.toString();
        System.err.println(hits);
        return hits;
    }

    private static String getJarPath() {
        String javaClazzPaths = System.getProperty("java.class.path");
        if (javaClazzPaths == null) {
            return Dep_Jar_Path;
        }
        String[] classPath = javaClazzPaths.split(File.pathSeparator);
        if (classPath == null) {
            return Dep_Jar_Path;
        }
        for (String cpEntry : classPath) {
            if (JAR_REGEX.matcher(cpEntry).matches()) {
                return cpEntry;
            }
        }
        return Dep_Jar_Path;
    }
}